package com.framework.buss.word.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.framework.buss.word.model.TemplateFile;
import com.framework.buss.word.model.TemplateSql;
import com.framework.buss.word.mapper.TemplateFileMapper;
import com.framework.buss.word.mapper.TemplateSqlMapper;
import com.framework.buss.word.service.IMonthReportService;
import com.framework.buss.word.util.ExportUtil;
import com.framework.common.domain.ResultData;
import com.framework.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MonthReportServiceImpl implements IMonthReportService {
    @Value("rootPath:/data/")
    private String rootPath;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TemplateFileMapper templateFileMapper;

    @Autowired
    private TemplateSqlMapper templateSqlMapper;

    /**
     * 导出模板（桥梁管理，模板管理，查询sql设置）
     * @param params 主要参数为哪座桥梁
     */
    @Override
    public void export(HttpServletResponse response, final Map<String, String> params) {
        Map data = new HashMap<>();
        QueryWrapper<TemplateFile> queryWrapper = new QueryWrapper<>();
        // 月度报表
        queryWrapper.eq("type", "reportMonth");
        // 根据类型查询当前的文件
        TemplateFile file = templateFileMapper.selectOne(queryWrapper);
        if (null == file) {
            throw new BusinessException("模板文件未上传");
        }
        QueryWrapper<TemplateSql> sqlParam = new QueryWrapper<>();
        sqlParam.eq("templateFileId", file.getId());
        List<TemplateSql> sqlList = templateSqlMapper.selectList(sqlParam);
        sqlList.forEach(it -> {
            String sql = it.getSql();
            if (it.isMultiple()) {
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
                data.put(it.getMultipleKeys(), list);
            } else {
                List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, params);
                if (list.size() >0) {
                    data.putAll(list.get(0));
                }
            }
        });
        ExportUtil.exportByTemplate(response, file.getName(), file.getCnName(), data);
    }

    @Override
    public ResultData importTemplate(MultipartFile file, TemplateFile fileInfo) {
        try {
            // 保存文件
            String path = rootPath.concat(fileInfo.getName());
            File descFile = new File(path);
            file.transferTo(descFile);
            // 保存文件信息
            templateFileMapper.insert(fileInfo);

            return ResultData.success("文件导入成功！");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            return ResultData.error("文件导入失败:"+e.getMessage());
        } finally {
            try {
                file.getInputStream().close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
    }
}
